const vscode = require('vscode');
const {translate} = require('./api');

//异常处理
function catchError(code) {
	const codes = {
		"52001": "请求超时,检查网络后重试" ,
		"52002": "系统错误, 查看百度翻译官网公告",
		"52003": "请检查appid或者服务是否开通",
		"54000": "必填参数为空",
		"54001": " 签名错误",
		"54003": "访问频率受限",
		"54004": "账户余额不足 ",
		"54005": "长query请求频繁, 请降低长query的发送频率，3s后再试 ",
		"58000": "客户端IP非法",
		"58001": "语言不支持",
		"58002": "服务当前已关闭, 请前往管理控制台开启服务",
		"90107": "认证未通过或未生效",
	  }
	  console.log(code, '进入到catchError');
	  vscode.window.showWarningMessage("aclfy_translate: " + codes[code] || "未知异常, 可评论git并反馈")
}

//中英文判断正则
function isChinese(str) {  
	let cleanedStr = str.replace(/[，。、\s]/g, '');
	return /^[\u4e00-\u9fa5]+$/.test(cleanedStr);  
}  
/**
 * @param {vscode.ExtensionContext} context
 */

function activate(context) {
	const disposable = vscode.commands.registerCommand('aclfy_translate.translate',  function () {
		let selectWord
		let editor = vscode.window.activeTextEditor;
		if (editor) {
			selectWord = editor.document.getText(editor.selection);
			if (selectWord) {
				const lang = isChinese(selectWord);
				// console.log(selectWord, lang, 'selectWord');
				translate(selectWord, lang).then(async (res) => {
					// console.log(res, 'res');
					if (res.error_code) {
						catchError(res.error_code)
					} else if (lang) {
						const result = res.trans_result[0].dst;
						// vscode.window.showInformationMessage(result);
						// 空格
						const list = result.split(' ')
						let word = ''
						console.log(list, 'list');
						if (list.length > 1) {
						const arr = []
						// 小驼峰
						arr.push(list.map((v, i) => {
							if (i !== 0) {
							return v.charAt(0).toLocaleUpperCase() + v.slice(1)
							}
							return v.toLocaleLowerCase()
						}).join(''))
						// - 号连接
						arr.push(list.map(v => v.toLocaleLowerCase()).join('-'))
						// 下划线连接
						arr.push(list.map(v => v.toLocaleLowerCase()).join('_'))
						// 大驼峰
						arr.push(list.map(v => v.charAt(0).toLocaleUpperCase() + v.slice(1)).join(''))
						word = await vscode.window.showQuickPick(arr, { placeHolder: '请选择要替换的变量名' })
						// console.log(word, 'word');
						} else {
						  word = list[0]
						//   console.log(word, 'word-else');
						}
						if (word) {
							editor.edit(editBuilder => {
							  editBuilder.replace(editor.selection, word)
							})
						}
					} else {
						const result = res.trans_result[0].dst;
						// vscode.window.showInformationMessage(result);
						editor.edit(editBuilder => {
							editBuilder.replace(editor.selection, result)
						})
					}
				}).catch((err) => {
					console.log(err, 'err');
					catchError(err.code)
				})
			}
		} else {
			vscode.window.showInformationMessage('未选择文本！');
		}
		vscode.window.showInformationMessage('Welcome to use aclfy_translate!');
	});

	context.subscriptions.push(disposable);
}

function deactivate() {}

module.exports = {
	activate,
	deactivate
}
